#!/usr/bin/python3

import uapool
import zjl_util
import re
import os
import time
import requests
import getopt
import sys


class TingShu8:
    """ download voice from ting89"""

    def __init__(self, u, d, offset):
        self.index_url = u
        self.dir = d
        self.start = offset
        if not os.path.exists(self.dir):
            os.makedirs(self.dir)
        uapool.UA()

    def get_file_info(self):
        """获取下载文件信息"""
        html = requests.get(self.index_url)
        # html.encoding = 'utf-8'
        json_text = html.text.encode('latin-1').decode('gbk')
        # print(doc)
        l_pat = '<div class="player"><a href="(.*?)".*?>(.*?)</a></div>'
        r = re.compile(l_pat, re.S).findall(json_text)
        print(r)
        print("------------------------------------------file_list")

        print(range(self.start, len(r)))
        for j in range(self.start, len(r)):
            print(j)
            i = r[j]
            file_name = i[1] + '.mp3'
            item_url = 'http:' + i[0]
            '''
            http://www.zgpingshu.com/play/4246/5.html
            转换为：
            http://www.zgpingshu.com/playdata/4246/5.html
            '''
            item_url = str(item_url).replace('play', 'playdata')
            # print('item_url:---------------------------\n' + item_url + '\n---------------------------')
            html = requests.get(item_url)
            # html.encoding = 'gbk'
            # json_text = html.text.encode('latin-1').decode('gbk')
            json_text = html.text
            print('############\n' + json_text)
            audio_pat = '"urlpath":"(.*?).flv"'
            rt = re.compile(audio_pat, re.S).findall(json_text)
            # print(r)
            mp3_url = rt[0] + '.mp3'
            print('---------------(' + file_name + ', ' + mp3_url + ")---------------")
            self.down_m4a(mp3_url, file_name)

    def down_m4a(self, file_url, file_name):
        """下载文件"""
        i = 0
        redo_count = 0  # 用于记录下载出现错误是记录重试次数，顺利下载完后，次数归0
        print('down: ' + file_url)
        while redo_count < 5:
            file_path = self.dir + "/" + file_name
            try:
                zjl_util.download(file_url, file_path)
                return
            except Exception as e:
                print("request error url:" + file_url)
                print(e)
                print('-------\t重试下载  ' + file_url + '  \t-------')
                redo_count += 1
                time.sleep(redo_count * 30 + 1) # 每次重试增加时间
                # 提前结束本次循环，再次下载这一章
                if redo_count >= 5:
                    print('[error] 多次重试后失败')
                    exit()


def main():
    index_url = "http://yueyu.zgpingshu.com/4246/"
    dir_path = "D:/data/薛丁山征西_林劲"
    offset = 0
    opts, args = getopt.getopt(sys.argv[1:], "hu:d:", ["offset="])
    for o, a in opts:
        if o == '-h':
            print("python3 down_yueyu.zgpingshu.py -u " + index_url + " -d " + dir_path + " --offset=" + str(offset))
            exit()
        if o == '-u':
            index_url = a
        if o == '-d':
            dir_path = a
        if o == '--offset':
            offset = int(a)
    print('目录地址：' + index_url)
    print('保存路径：' + dir_path)
    app = TingShu8(index_url, dir_path, offset)
    app.get_file_info()


if __name__ == '__main__':
    main()
